import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/redux/store';
import { Student } from '@/types';
import '@/styles/pages/studentManage.scss';

// 导入服务函数
import { getStudentList } from '@/services/student';
import { getClasses, createStudent, updateStudent, deleteStudent } from '@/services/class';

const StudentManageNew: React.FC = () => {
  const [students, setStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [classes, setClasses] = useState<{id: number, name: string}[]>([]);
  const [selectedClassId, setSelectedClassId] = useState<number | null>(null);
  
  // 模态框相关状态
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'edit'>('create');
  const [editingStudent, setEditingStudent] = useState<Student | null>(null);
  
  // 表单状态
  const [studentId, setStudentId] = useState('');
  const [studentName, setStudentName] = useState('');
  const [formError, setFormError] = useState('');

  const { teacher } = useSelector((state: RootState) => state.auth);

  useEffect(() => {
    fetchClasses();
  }, []);

  useEffect(() => {
    if (selectedClassId) {
      fetchStudents(selectedClassId);
    }
  }, [selectedClassId]);

  const fetchClasses = async () => {
    try {
      setLoading(true);
      setError('');
      // 调用获取班级列表的API
      const res = await getClasses();
      console.log('获取班级列表结果:', res);
      
      if (res.code === 2000) {
        setClasses(res.data?.classes || []);
        // 如果有班级，默认选中第一个
        if (res.data?.classes && res.data.classes.length > 0) {
          setSelectedClassId(res.data.classes[0].id);
        }
      } else {
        setError(res.message || '获取班级列表失败');
      }
    } catch (err: any) {
      console.error('获取班级列表出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const fetchStudents = async (classId: number) => {
    try {
      setLoading(true);
      setError('');
      
      // 使用班级ID获取学生列表
      const res = await getStudentList(classId);
      console.log('获取学生列表结果:', res);
      
      if (res.code === 2000) {
        setStudents(res.data?.students || []);
      } else {
        setError(res.message || '获取学生列表失败');
      }
    } catch (err: any) {
      console.error('获取学生列表出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleClassChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSelectedClassId(Number(e.target.value));
  };

  // 打开创建学生模态框
  const handleOpenCreateModal = () => {
    setModalType('create');
    setStudentId('');
    setStudentName('');
    setFormError('');
    setShowModal(true);
  };

  // 打开编辑学生模态框
  const handleOpenEditModal = (student: Student) => {
    setModalType('edit');
    setEditingStudent(student);
    setStudentId(student.student_id);
    setStudentName(student.name);
    setFormError('');
    setShowModal(true);
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setShowModal(false);
  };

  // 创建或更新学生
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError('');

    if (!studentId.trim()) {
      setFormError('请输入学号');
      return;
    }

    if (!studentName.trim()) {
      setFormError('请输入姓名');
      return;
    }

    if (!selectedClassId) {
      setFormError('请选择班级');
      return;
    }

    try {
      if (modalType === 'create') {
        // 创建学生
        console.log('提交创建学生:', { studentId, studentName });
        const res = await createStudent(studentId, studentName);
        console.log('创建学生结果:', res);
        
        if (res.code === 2000) {
          setShowModal(false);
          // 刷新学生列表
          fetchStudents(selectedClassId);
        } else {
          setFormError(res.message || '创建学生失败');
        }
      } else if (modalType === 'edit' && editingStudent) {
        // 更新学生
        console.log('提交更新学生:', { id: editingStudent.id, studentId, studentName, selectedClassId });
        const res = await updateStudent(
          editingStudent.id, 
          studentId, 
          studentName, 
          selectedClassId
        );
        console.log('更新学生结果:', res);
        
        if (res.code === 2000) {
          setShowModal(false);
          // 刷新学生列表
          fetchStudents(selectedClassId);
        } else {
          setFormError(res.message || '更新学生失败');
        }
      }
    } catch (err: any) {
      console.error('操作学生信息出错:', err);
      setFormError(err.message || '网络错误，请稍后重试');
    }
  };

  // 删除学生
  const handleDeleteStudent = async (studentId: number) => {
    if (window.confirm('确定要删除该学生吗？')) {
      try {
        console.log('删除学生:', studentId);
        const res = await deleteStudent(studentId);
        console.log('删除学生结果:', res);
        
        if (res.code === 2000) {
          // 刷新学生列表
          if (selectedClassId) {
            fetchStudents(selectedClassId);
          }
        } else {
          alert(res.message || '删除学生失败');
        }
      } catch (err: any) {
        console.error('删除学生出错:', err);
        alert(err.message || '网络错误，请稍后重试');
      }
    }
  };

  return (
    <div className="student-manage-container">
      <div className="page-header">
        <h1>学生管理</h1>
        <button 
          className="btn btn-primary"
          onClick={handleOpenCreateModal}
          disabled={!selectedClassId}
        >
          添加学生
        </button>
      </div>
      
      {error && <div className="error-message">{error}</div>}

      <div className="class-selector">
        <label htmlFor="class-select">选择班级：</label>
        <select 
          id="class-select" 
          value={selectedClassId || ''} 
          onChange={handleClassChange}
          disabled={loading || classes.length === 0}
        >
          {classes.length === 0 ? (
            <option value="">暂无班级</option>
          ) : (
            classes.map(cls => (
              <option key={cls.id} value={cls.id}>
                {cls.name}
              </option>
            ))
          )}
        </select>
      </div>
      
      <div className="student-list-wrapper">
        {loading ? (
          <div className="loading">加载中...</div>
        ) : students.length > 0 ? (
          <table className="student-table">
            <thead>
              <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {students.map((student) => (
                <tr key={student.id}>
                  <td>{student.student_id}</td>
                  <td>{student.name}</td>
                  <td className="action-cell">
                    <button 
                      className="btn btn-sm btn-default"
                      onClick={() => handleOpenEditModal(student)}
                    >
                      编辑
                    </button>
                    <button 
                      className="btn btn-sm btn-danger"
                      onClick={() => handleDeleteStudent(student.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="empty-tip">
            暂无学生数据
            {selectedClassId && (
              <button 
                className="btn btn-primary"
                onClick={handleOpenCreateModal}
              >
                添加学生
              </button>
            )}
          </div>
        )}
      </div>

      {/* 学生信息模态框 */}
      {showModal && (
        <div className="modal-overlay">
          <div className="modal-content">
            <div className="modal-header">
              <h2>{modalType === 'create' ? '添加学生' : '编辑学生'}</h2>
              <button 
                className="close-btn"
                onClick={handleCloseModal}
              >
                &times;
              </button>
            </div>
            
            {formError && <div className="error-message">{formError}</div>}
            
            <form onSubmit={handleSubmit}>
              <div className="form-item">
                <label htmlFor="studentId">学号</label>
                <input
                  id="studentId"
                  type="text"
                  value={studentId}
                  onChange={(e) => setStudentId(e.target.value)}
                  placeholder="请输入学号"
                />
              </div>
              
              <div className="form-item">
                <label htmlFor="studentName">姓名</label>
                <input
                  id="studentName"
                  type="text"
                  value={studentName}
                  onChange={(e) => setStudentName(e.target.value)}
                  placeholder="请输入姓名"
                />
              </div>
              
              <div className="form-item">
                <label htmlFor="studentClass">班级</label>
                <select
                  id="studentClass"
                  value={selectedClassId || ''}
                  disabled={true} // 在编辑时不允许修改班级
                >
                  {classes.map(cls => (
                    <option key={cls.id} value={cls.id}>
                      {cls.name}
                    </option>
                  ))}
                </select>
              </div>
              
              <div className="form-actions">
                <button 
                  type="button" 
                  className="btn btn-default"
                  onClick={handleCloseModal}
                >
                  取消
                </button>
                <button type="submit" className="btn btn-primary">
                  {modalType === 'create' ? '添加' : '保存'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default StudentManageNew; 